﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;
using CalemShop.Forms;
using System.Threading;
using System.Media;
using CalemShop.Classes;

namespace CalemShop
{
    public partial class FrmCheckStock : FrmBaseDock
    {
        Color defaultColor = Color.Black;
        private Dictionary<string, DataRow> cacheStock = new Dictionary<string, DataRow>();
        private Dictionary<string, DataRow> cacheStockBarcode = new Dictionary<string, DataRow>();
        private bool memberCheckBarcode = false;
        private SoundPlayer sound = null;
        public FrmCheckStock()
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            listBranch.Items.AddRange(RuntimeData.GetCalemBranchList());
            sound = new SoundPlayer(RuntimeData.GetSoundCompletePath());

        }

        public FrmCheckStock(FrmCalemShop shop)
            : base(shop)
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            listBranch.Items.AddRange(RuntimeData.GetCalemBranchList());
            sound = new SoundPlayer(RuntimeData.GetSoundCompletePath());
        }


        private void FrmCheckStock_Load(object sender, EventArgs e)
        {
            DataTable sr = Database.getItemType();
            ItemType[] typeList = new ItemType[sr.Rows.Count];
            int c = 0;
            foreach (DataRow r in sr.Rows)
            {
                ItemType t = new ItemType(Int32.Parse(r["typeId"].ToString()), r["typeName"].ToString());
                typeList[c++] = t;
            }

            chItems.Items.AddRange(typeList);

            chGender.Items.AddRange(new Gender[] { new Gender("Trai", "T"), new Gender("Gái", "G") });

            txtSearch.AutoCompleteCustomSource = Database.itemNameCollection;

            LockWaitOrRelease(true);
            listBranch.Enabled = true;
        }

        private void btFilterType_Click(object sender, EventArgs e)
        {
            doApplyFilter();

        }


        private void stockView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == check.Index)
            {
                DataGridViewCell cell = stockView[check.Index, e.RowIndex];
                int value = 0;
                if (cell.Value != null)
                {
                    value = Int32.Parse(cell.Value.ToString());
                }
                DataRowView r = stockView.CurrentRow.DataBoundItem as DataRowView;
                if (value == 1)
                {
                    if (defaultColor == Color.Black)
                    {
                        defaultColor = stockView.CurrentRow.DefaultCellStyle.BackColor;
                    }

                    stockView.CurrentRow.DefaultCellStyle.BackColor = Color.Yellow;
                    if (cacheStock.ContainsKey(r.Row["autoKey"].ToString()) == false)
                    {
                        cacheStock.Add(r.Row["autoKey"].ToString(), r.Row);
                    }
                }
                else
                {
                    if (defaultColor != Color.Black)
                    {
                        stockView.CurrentRow.DefaultCellStyle.BackColor = defaultColor;
                    }

                    cacheStock.Remove(r.Row["autoKey"].ToString());
                }

                int selectedCount = 0;
                int printingItem = 0;
                foreach (DataRow rw in cacheStock.Values)
                {
                    selectedCount++;
                    printingItem += Int32.Parse(rw["amount"].ToString());
                }

                string format = lbMessage.Tag.ToString();
                lbMessage.Text = string.Format(format, selectedCount, printingItem);
            }
        }

        private void btReset_Click(object sender, EventArgs e)
        {
            ArrayList sqls = new ArrayList();
            sqls.Add("update shop_stock set `check` = 0;");
            DataManager.BranchExecuteQuerys(sqls, null);
            doApplyFilter();
        }

        private void btCheckAmount_Click(object sender, EventArgs e)
        {
            if (DataManager.BranchExecuteQuerys("update shop_stock set amount = 0 where amount < 0;") > 0)
            {
                doApplyFilter();
            }
        }

        private void doApplyFilter()
        {
            try
            {
                lbMessage.Text = string.Empty;
                StringBuilder filter = new StringBuilder("");
                bool hasTypeFilter = false;
                if (chItems.CheckedItems != null && chItems.CheckedItems.Count > 0)
                {
                    hasTypeFilter = true;
                    filter.Append(" where (");
                    for (int i = 0; i < chItems.CheckedItems.Count - 1; i++)
                    {
                        ItemType t = (ItemType)chItems.CheckedItems[i];
                        filter.AppendFormat("`type` = {0} or ", t.typeId);
                    }

                    ItemType lastT = (ItemType)chItems.CheckedItems[chItems.CheckedItems.Count - 1];
                    filter.AppendFormat("`type` = {0})", lastT.typeId);
                }


                if (chGender.CheckedItems != null && chGender.CheckedItems.Count > 0)
                {
                    if (hasTypeFilter)
                    {
                        filter.Append(" and (");
                    }
                    else
                    {
                        filter.Append(" where (");
                    }

                    for (int i = 0; i < chGender.CheckedItems.Count - 1; i++)
                    {
                        Gender t = (Gender)chGender.CheckedItems[i];
                        filter.AppendFormat("`gender` = '{0}' or ", t.GenderValue);
                    }

                    Gender lastT = (Gender)chGender.CheckedItems[chGender.CheckedItems.Count - 1];
                    filter.AppendFormat("`gender` = '{0}')", lastT.GenderValue);


                }

                //MessageBox.Show(filter.ToString());
                DataTable sr = DataManager.BranchGetStockBy(filter.ToString());
                bindingSourceStock.DataSource = sr;
                bindingSourceStock.ResetBindings(true);
                cacheStock.Clear();
            }
            catch (Exception)
            {
            }
        }

        private void stockView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }

            if (memberCheckBarcode)
            {
                chBarcode.Checked = true;
                memberCheckBarcode = false;
            }

            // Dieu chinh gia ban.
            if (stockView[e.ColumnIndex, e.RowIndex].Value != null && e.ColumnIndex == price.Index)
            {
                stockView.CommitEdit(DataGridViewDataErrorContexts.Commit);
                string sql = "update shop_stock set price = " + stockView[e.ColumnIndex, e.RowIndex].Value + " where autoKey =" + stockView[autoKey.Index, e.RowIndex].Value;
                DataManager.BranchExecuteQuerys(sql);
            }
            else if (stockView[e.ColumnIndex, e.RowIndex].Value != null && e.ColumnIndex == type.Index)
            {
                // Dieu chinh loai
                stockView.CommitEdit(DataGridViewDataErrorContexts.Commit);
                string sql = "update shop_stock set type = " + stockView[e.ColumnIndex, e.RowIndex].Value + " where autoKey =" + stockView[autoKey.Index, e.RowIndex].Value;
                DataManager.BranchExecuteQuerys(sql);
            }
        }

        private void chBarcode_CheckedChanged(object sender, EventArgs e)
        {
            txtBarcode.Enabled = chBarcode.Checked;
            btSave.Enabled = chBarcode.Checked;
            btOpen.Enabled = chBarcode.Checked;
            if (chBarcode.Checked)
            {
                txtBarcode.Focus();
                DataTable sr = (DataTable)bindingSourceStock.DataSource;
                if (sr != null)
                {
                    sr.Clear();
                    if (!sr.Columns.Contains("checkAmount"))
                    {
                        sr.Columns.Add("checkAmount", Type.GetType("System.Int32"));
                    }
                }

                if (MessageBox.Show(this, "Chức năng này sẽ kiểm tra số lượng tồn của sản phẩm, Bạn có đồng ý không ?", "Cảnh báo", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    string sql = "update shop_stock set `check` = 0;";
                    cacheStock.Clear();
                    cacheStockBarcode.Clear();
                    DataManager.BranchExecuteQuerys(sql);
                    lbMessage.Text = string.Empty;
                    checkAmount.Visible = true;
                }
                else
                {
                    chBarcode.Checked = false;
                }
            }
            else
            {
                checkAmount.Visible = false;
            }
        }

        private void txtBarcode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    txtBarcode.Text = txtBarcode.Text.Replace("'", "");
                    string barcode = txtBarcode.Text;
                    DataRow checkRow = null;
                    DataTable sr = (DataTable)bindingSourceStock.DataSource;
                    if (sr == null)
                    {
                        sr = DataManager.BranchGetStockBy("where autoKey=" + txtBarcode.Text);
                        if (sr == null)
                        {
                            return;
                        }

                        if (!sr.Columns.Contains("checkAmount"))
                        {
                            sr.Columns.Add("checkAmount", Type.GetType("System.Int32"));
                        }
                        bindingSourceStock.DataSource = sr;
                        bindingSourceStock.ResetBindings(true);
                        if (sr.Rows.Count > 0)
                        {
                            checkRow = sr.Rows[0];
                            int amount = 0;
                            Int32.TryParse(checkRow["checkAmount"].ToString(), out amount);
                            amount++;
                            checkRow["checkAmount"] = amount;
                            cacheStockBarcode[barcode] = sr.Rows[0];
                            //FrmCheckAmountItem frms = new FrmCheckAmountItem();
                            //frms.setInfo(txtBarcode.Text, checkRow["itemName"].ToString(), Int32.Parse(checkRow["amount"].ToString()), checkRow["size"].ToString());
                            //frms.ShowDialog(this);
                            //string sql = "update shop_stock set amount = " + amount + " where autoKey =" + barcode;
                            //Database.executeQuerys(sql);
                        }

                        return;
                    }


                    if (!cacheStockBarcode.ContainsKey(barcode))
                    {
                        int keycode = 0;
                        Int32.TryParse(txtBarcode.Text, out keycode);
                        ItemEntity item = DataManager.BranchGetStockItem(keycode);
                        if (item == null)
                        {
                            return;
                        }

                        DataRow r = sr.NewRow();
                        r["autoKey"] = item.autoKey;
                        r["amount"] = item.amount;
                        r["itemName"] = item.name;
                        r["color"] = item.color;
                        r["type"] = item.type;
                        r["size"] = item.size;
                        r["supplier"] = item.supplier;
                        r["gender"] = item.gender;
                        r["checkAmount"] = 1;
                        r["price"] = item.price;
                        sr.Rows.Add(r);
                        cacheStockBarcode[barcode] = r;
                        checkRow = r;
                    }
                    else
                    {
                        checkRow = cacheStockBarcode[barcode];
                        int amount = 0;
                        Int32.TryParse(checkRow["checkAmount"].ToString(), out amount);
                        checkRow["checkAmount"] = amount + 1;
                    }

                    //FrmCheckAmountItem frm = new FrmCheckAmountItem();
                    //frm.setInfo(txtBarcode.Text, checkRow["itemName"].ToString(), Int32.Parse(checkRow["amount"].ToString()), checkRow["size"].ToString());
                    //frm.ShowDialog(this);
                    //string updateSql = "update shop_stock set amount = " + checkRow["amount"] + " where autoKey =" + barcode;
                    //Database.executeQuerys(updateSql);

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.StackTrace);
                }
                finally
                {
                    txtBarcode.Text = string.Empty;
                }

            }
        }

        private void btNewItemToday_Click(object sender, EventArgs e)
        {
            String t = dateTimePicker.Value.ToString("yyyy-MM-dd 00:00:00");
            string sql = "where DATE(createTime) = DATE('" + t + "')";
            bindingSourceStock.DataSource = DataManager.BranchGetStockBy(sql);
            bindingSourceStock.ResetBindings(true);
        }

        private void btPrint_Click(object sender, EventArgs e)
        {
            CalemShop.ShowBarcodePrinter();
            FrmBarcodePrinter print = CalemShop.BarcodePrinter;
            try
            {
                DataTable sr = (DataTable)bindingSourceStock.DataSource;
                if (sr == null || sr.Rows.Count == 0)
                {
                    return;
                }

                ArrayList list = new ArrayList();
                Hashtable itemMap = new Hashtable();
                foreach (DataRow r in sr.Rows)
                {
                    if (Int32.Parse(r["check"].ToString()) == 1)
                    {
                        int amount = Int32.Parse(r["amount"].ToString());
                        if (amount == 0)
                        {
                            list.Add(r["autoKey"].ToString());
                        }
                        else
                        {
                            for (int i = 0; i < amount; i++)
                            {
                                list.Add(r["autoKey"].ToString());
                            }
                        }

                        itemMap[r["autoKey"].ToString()] = r["price"];
                    }
                }

                if (list.Count > 0)
                {
                    list.Sort();
                    print.itemMap = itemMap;
                    print.barcodeValues = list;
                    print.doCalculatorPages();
                    print.txtFromMSP.Enabled = false;
                    print.txtToMSP.Enabled = false;
                    print.useFromInputStock = true;
                }

                print.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btSearch_Click(object sender, EventArgs e)
        {
            doSearch();
        }

        private void txtSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                doSearch();
            }
        }

        private void doSearch()
        {
            try
            {
                if (string.IsNullOrEmpty(txtSearch.Text))
                {
                    return;
                }

                string value = txtSearch.Text.Replace("'", "");
                int num = 0;
                Int32.TryParse(value, out num);

                string where = "where itemName like '%" + value + "%' or itemId like '%" + value + "%'";
                if (num != 0)
                {
                    where = "where autoKey=" + num + " or itemName like '%" + value + "%' or itemId like '%" + value + "%'";
                }

                DataTable sr = DataManager.BranchGetStockBy(where);
                if (sr != null)
                {
                    cacheStock.Clear();
                    bindingSourceStock.DataSource = sr;
                    bindingSourceStock.ResetBindings(true);
                }

                //if (Database.itemNameCollection.Count == 0)
                //{
                //    Database.getAllItemIds();
                //}
            }
            catch (Exception)
            {
            }
        }

        private void btSave_Click(object sender, EventArgs e)
        {
            if (chBarcode.Checked)
            {
                try
                {
                    DataTable sr = (DataTable)bindingSourceStock.DataSource;
                    if (sr != null)
                    {
                        sr.TableName = "CheckStock";
                        saveFileDialog1.InitialDirectory = BackupUtil.doCheckWorkspace();
                        if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
                        {
                            string fileName = saveFileDialog1.FileName;
                            sr.WriteXml(fileName, System.Data.XmlWriteMode.WriteSchema);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void btOpen_Click(object sender, EventArgs e)
        {
            if (chBarcode.Checked)
            {
                try
                {

                    openFileDialog1.InitialDirectory = BackupUtil.doCheckWorkspace();
                    if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
                    {
                        string fileName = openFileDialog1.FileName;
                        DataTable sr = new DataTable();
                        sr.TableName = "CheckStock";
                        sr.ReadXml(fileName);
                        bindingSourceStock.DataSource = sr;
                        bindingSourceStock.ResetBindings(true);
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void chCost_CheckedChanged(object sender, EventArgs e)
        {

            if (chCost.Checked)
            {
                FrmLogin frmLogin = new FrmLogin();
                if (frmLogin.ShowDialog(this) == DialogResult.OK && frmLogin.loginOk && frmLogin.isAdmin)
                {
                    cost.Visible = chCost.Checked;
                }
                else
                {
                    MessageBox.Show(this, "Cần phải đăng nhập mới sử dụng được tính năng này.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                cost.Visible = false;
            }
        }

        private void stockView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex == check.Index)
            {
                stockView.InvalidateRow(e.RowIndex);
            }
        }

        private void LockWaitOrRelease(bool isLock)
        {
            this.listBranch.Enabled = !isLock;
            this.stockView.Enabled = !isLock;
            this.toolStrip1.Enabled = !isLock;
            this.btNewItemToday.Enabled = !isLock;
            this.btPrint.Enabled = !isLock;
            this.btReset.Enabled = !isLock;
            this.btFilterType.Enabled = !isLock;
            this.btCheckAmount.Enabled = !isLock;
            this.chItems.Enabled = !isLock;
            this.chGender.Enabled = !isLock;
        }

        private void listBranch_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(listBranch.Text))
            {
                return;
            }

            this.Enabled = false;
            try
            {
                this.UseWaitCursor = true;
                string connectionString = RuntimeData.GetDBBranchConnection(listBranch.Text);
                if (string.IsNullOrEmpty(connectionString))
                {
                    MessageBox.Show(this, string.Format("Không thể kết nối tới [{0}]", listBranch.Text), "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                DBBranchConnection.ConnectionString = connectionString;
                if (DBBranchConnection.TestConnection())
                {
                    PlayCompleteSound();
                    // Load data here :
                    MessageBox.Show(this, string.Format("Kết nối thành công tới chi nhánh [{0}]", listBranch.Text), "Thông báo", MessageBoxButtons.OK);

                }
                else
                {
                    MessageBox.Show(this, string.Format("Không thể kết nối tới [{0}]", listBranch.Text), "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            finally
            {
                this.Enabled = true;
                this.UseWaitCursor = false;
                LockWaitOrRelease(false);
            }
        }

        private void PlayCompleteSound()
        {
            try
            {
                this.sound.PlaySync();
            }
            catch (Exception e)
            {
            }
        }

        public override void FormActived()
        {
            base.FormActived();
            string connectionString = RuntimeData.GetDBBranchConnection(listBranch.Text);
            if (!string.IsNullOrEmpty(connectionString))
            {
                DBBranchConnection.ConnectionString = connectionString;
            }
        }

    } //class
}
